package com.loan.system.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.loan.common.core.domain.PageQuery;
import com.loan.common.core.page.TableDataInfo;
import com.loan.common.enums.SmsCompanyType;
import com.loan.common.enums.SmsTemplateType;
import com.loan.common.sms.SmsUtils;
import com.loan.system.domain.SmsConfigEntity;
import com.loan.system.domain.SmsTemplateEntity;
import com.loan.system.mapper.PayBankMapper;
import com.loan.system.mapper.SmsConfigMapper;
import com.loan.system.mapper.SmsTemplateMapper;
import com.loan.system.service.SmsConfigService;
import com.loan.system.service.SmsSendLogService;
import com.loan.system.service.SmsTemplateService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;

/**
 * @author shiguang on 2022/9/15 15:40
 */
@Service
@RequiredArgsConstructor
public class SmsTemplateServiceImpl implements SmsTemplateService {

    private final SmsTemplateMapper smsTemplateMapper;

    private final SmsConfigMapper smsConfigMapper;

    private final SmsSendLogService smsSendLogService;

    @Override
    public TableDataInfo<SmsTemplateEntity> selectPageList(SmsTemplateEntity entity, PageQuery pageQuery) {
        Page<SmsTemplateEntity> page = smsTemplateMapper.selectPageList(pageQuery.build(), this.buildQueryWrapper(entity));
        return TableDataInfo.build(page);
    }

    @Override
    public SmsTemplateEntity selectSmsTemplateById(Long id) {
        return smsTemplateMapper.selectById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertSmsTemplate(SmsTemplateEntity entity) {
        SmsTemplateEntity smsTemplateEntity = smsTemplateMapper.selectOne(new QueryWrapper<SmsTemplateEntity>()
                .eq("del_flag", "0")
                .eq("status", "0")
                .eq("type", entity.getType()));
        if (ObjectUtil.isNotNull(smsTemplateEntity)) {
            entity.setStatus("1");
        }
        return smsTemplateMapper.insert(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateSmsTemplate(SmsTemplateEntity entity) {
        return smsTemplateMapper.updateById(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteSmsTemplateById(Long id) {
        return smsTemplateMapper.deleteById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateSmsTemplateStatus(SmsTemplateEntity entity) {
        if (entity.getStatus().equals("0")) {
            SmsTemplateEntity smsTemplateEntity = smsTemplateMapper.selectOne(new QueryWrapper<SmsTemplateEntity>()
                    .eq("del_flag", "0")
                    .eq("status", "0")
                    .ne("id", entity.getId())
                    .eq("type", entity.getType()));
            if (ObjectUtil.isNotNull(smsTemplateEntity)) {
                smsTemplateEntity.setStatus("1");
                smsTemplateMapper.updateById(smsTemplateEntity);
            }
        }
        return smsTemplateMapper.updateById(entity);
    }

    /**
     * 发送到期前一天短信
     *
     * @param mobile
     * @param type
     * @param params
     * @return
     */
    @Override
    public boolean sendSms(String mobile, String type, Map<String, Object> params) {
        Boolean result = false;
        String companyName = "";
        //获取营销模板
        SmsTemplateEntity smsTemplateEntity = smsTemplateMapper.selectOne(new QueryWrapper<SmsTemplateEntity>().eq("type", type)
                .eq("status", "0")
                .eq("del_flag", "0"));
        if (ObjectUtil.isNotNull(smsTemplateEntity)) {
            //查找营销短信通道
            SmsConfigEntity configEntity = smsConfigMapper.selectOne(new QueryWrapper<SmsConfigEntity>().eq("type", "1")
                    .eq("del_flag", "0")
                    .eq("status", "0"));
            if (ObjectUtil.isNotNull(configEntity)) {
                String content = com.loan.common.utils.StringUtils.processTemplate(smsTemplateEntity.getContent(), params);
                if (configEntity.getCompanyType().equals(SmsCompanyType.NX.getCode())) {
                    companyName = SmsCompanyType.NX.getInfo();
                    result = SmsUtils.sendSms(configEntity.getApiUrl(), configEntity.getAppKey(), configEntity.getSecretKey(), mobile, content);
                } else if (configEntity.getCompanyType().equals(SmsCompanyType.TYH.getCode())) {
                    result = SmsUtils.sendSmsNew(configEntity.getApiUrl(), configEntity.getAppKey(), configEntity.getSecretKey(), configEntity.getAppId(), mobile, content);
                    companyName = SmsCompanyType.TYH.getInfo();
                }
                smsSendLogService.asyncSaveSendLog(type, companyName, content, mobile, result);
                return result;
            }
        }
        return result;
    }

    private Wrapper<SmsTemplateEntity> buildQueryWrapper(SmsTemplateEntity entity) {
        Map<String, Object> params = entity.getParams();
        QueryWrapper<SmsTemplateEntity> wrapper = Wrappers.query();
        wrapper.eq("del_flag", 0)
                .eq(StringUtils.isNotBlank(entity.getType()), "type", entity.getType())
                .orderByDesc("create_time");
        return wrapper;
    }
}
